#!/usr/bin/perl


our $logs_dir='logs';

our $exploit=shift;
our $log=$logs_dir . '/' . $exploit . '.txt';

our $team='Hackerdom';
our $sleep_before_next_loop=1;
our $teams_file='teams.txt';

our $vulnerable_box_suffix='3';

our %teams_pid;

use POSIX ":sys_wait_h";

start();
$SIG{CHLD} = \&REAPER;
serve();


sub REAPER
{
    my $child;
    my $team;
    # If a second child dies while in the signal handler caused by the
    # first death, we won't get another signal. So must loop here else
    # we will leave the unreaped child as a zombie. And the next time
    # two children die we get another zombie. And so on.
    while (($child = waitpid(-1,WNOHANG)) > 0)
    {
	#$Kid_Status{$child} = $?;
	my $status=$?;
	$team=$teams_pid{$child};
	print "-- Team $team loop end. Status: $status\n";
	print "Somthing wrong in script with team $team\n" if ($status != 0);
	delete $teams_pid{$child};

	doit_start($team);
    } 
    $SIG{CHLD} = \&REAPER;  # still loathe sysV
}
$SIG{CHLD} = \&REAPER;


sub doit_one
{
    my $team=shift;
    print ">>>Team $team next loop!\n";
    system("$cmd $team >> $log");
    my $status=$?;
    print "\t\tTeam $team ends loop and relaxing a bit before next\n";
    sleep($sleep_before_next_loop);
    print "\t\tTeam $team > next loop!\n";
    exit($status);
}

sub doit_start
{
    my $team=shift;
    my $pid=fork();

    if ($pid > 0) #parent
    {
	$teams_pid{$pid}=$team;
    }elsif ($pid==0) #child
    {
	
	doit_one($team);
    }else #error
    {
	print "Internal Error: Can`t fork!\n";
	return 1;
    }
    return 0;
}

sub start
{
    print "Starting...\n";
    open F,$teams_file or die "Can`t open team file '$teams_file' : $!\n";
    while (<F>)
    {
	next if (/^#/);
	chomp;
	/^(.+?)\t+(.+)$/;
	$t=$1;
	$ip=$2;
	next if ($t =~ /^$team$/i);
	$ip.=$vulnerable_box_suffix;
	print "Starting '$1' team, IP: '$ip'\n";
        doit_start($ip);
    }
}

sub serve
{
    while (1)
    {
	sleep 12000; #do nothing :) Just waiting for signal
    }
}
